#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

void child_write(int fd)
{
    char c = 0;
    int cnt = 0;
    while(true)
    {
        write(fd,&c,1);
        printf("child: %d\n", cnt++);
        if(cnt == 5)
        {
            break;
        }
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while (true)
    {
        sleep(10);
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say: " << buffer << std::endl;
            // sleep(2);
        }
        else if(n == 0)
        {
            std::cout << "n : " << n << std::endl;
            std::cout << "child 退出，我也退出";
            break;
        }
        else
        {
            break;
        }
    }
}
int main()
{
    int fds[2] = {0};
    int n = pipe(fds);
    std::cout << fds[0] << " " << fds[1] << std::endl;
    pid_t id = fork();
    if(id == 0)
    {
        close(fds[0]);
        child_write(fds[1]);
        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    return 0;
}
